﻿using DL.Animation;
using DL.Combat.Base.Data;
using DL.Health.Interface;
using DL.Tools;
using Messegers;
using Tools.Unilts;
using UnityEngine;

namespace DL.Health
{
    public class CharacterHealthBase : IDamageable
    {
        protected Transform CurrentAttacker;
        protected Animator Animator;
        protected Transform Self;
        
        protected CharacterHealthData CharacterHealth;
        
        protected int GodLayer;
        protected int MySelfLayer;

        public CharacterHealthBase(Characters.Actor actor)
        {
            Animator = actor.Animator;
            Self = actor.Self;

            CharacterHealth = new(actor.CharacterSO.HealthConfig.MaxHP, actor.CharacterSO.HealthConfig.MaxStrenth);
        }
        
        /// <summary>
        /// 重设重生数据
        /// </summary>
        public void Reset()
        {
            CharacterHealth.Reset();
            SetAttacker(null);
            SetCharacterLayer(MySelfLayer);
        }

        /// <summary>
        /// 该状态下可以存在行为回调注册
        /// </summary>
        public virtual void AddInputActionCallBacks()
        {
            Messenger<CombatActionSO, int, Transform, Transform>.AddListener(MessengerName.MSG_HurtEvt, TriggerDamaged);
        }


        /// <summary>
        /// 该状态下退出移除行为回调注册
        /// </summary>
        public virtual void RemoveInputActionCallBacks()
        {
            Messenger<CombatActionSO, int, Transform, Transform>.RemoveListener(MessengerName.MSG_HurtEvt, TriggerDamaged);
        }
        
        public void TriggerDamaged(CombatActionSO combatAction, int hitcount, Transform attacker, Transform target)
        {
            if (!Self.Equals(target)) return;
            SetAttacker(attacker);
            CharacterHit(combatAction.ComboHitName[hitcount], combatAction.ComboParryName[hitcount],
                combatAction.ActionDamage[hitcount]);
        }
        
        public void OnHitLookAttacker()
        {
            if (Animator.CheckAnimationTag(AnimatorTag.Hit) || Animator.CheckAnimationTag(AnimatorTag.Parry))
            {
                if (Animator.AnimationNormalTime() < .7f)
                {
                    Self.Look(DevelopmentToos.CalculateDirection(CurrentAttacker, Self));
                }
            }
        }
        
        protected virtual void Damaged(float damaged)
        {
            //扣除生命值，播放音效
            
        }
        
        protected void SetCharacterLayer(int layer)
        {
            Self.gameObject.layer = layer;
        }

        protected virtual void CharacterHit(string hitName,string parryName,float damaged)
        {
            
        }
        
        protected void SetAttacker(Transform attacker)
        {
            CurrentAttacker = (CurrentAttacker != attacker) ? attacker : CurrentAttacker;
        }

    }
}